package zzu.mxd.config.interceptors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import zzu.mxd.utils.HttpClient;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by zwl on 2018/11/11.
 * May god bless me
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private HttpClient httpClient;

    @Value("${spring.security.timeOutMilliSeconds}")
    private long timeOutMilliSeconds;



    //这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getParameter("userId");
        String openId;
        String stamp = request.getParameter("timeStamp");

        if (stamp != null && !stamp.equals("")) {
            //转化
            Long timeStamp = Long.parseLong(stamp);
            //检测时间
            if (timeStamp - System.currentTimeMillis() <= timeOutMilliSeconds) {
                //检测UserId
                if (userId != null && !userId.equals("")) {
                    openId = httpClient.getOpenId(request, response);
                    if (openId != null) {
                        //登陆Set redis
                        request.setAttribute("openId", openId);
                        return true;
                    } else {
                        response.sendError(300, "获取不到openID");
                        return false;
                    }
                } else {
                    response.sendError(300, "不存在的用户");
                    return false;
                }
            } else {
                response.sendError(300, "请求超时");
                return false;
            }
        } else {
            response.sendError(300, "时间参数获取错误");
            return false;
        }

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }

}
